var webcfg = window.NameSpace || {};

/*初始化，读取后台配置保存在localStorage中*/
webcfg.init = function () {

    var root = cfg.getBasePath();
    var configFilePath = root + "webconfig.txt?t=" + Math.random();

    $.ajax({
        url: configFilePath,
        type: 'get',
        async: false,//使用同步的方式,true为异步方式
        data: {},//这里使用json对象
        dataType: "json",
        success: function (data) {
            //console.log(data);

            webcfg.load(data);
        },
        fail: function () {
            //code here...
            console.log("cfg加载客户端配置文件jsconfig.txt失败");
            
        }
    });
}

webcfg.load = function (configinfo) {
    //console.log(configinfo);

    var svcURL = configinfo.config_uri + "config/" +
        configinfo.config_name + "/" +
        configinfo.config_profile + "/" +
        configinfo.config_label + "?t=" + Math.random();
    
    $.ajax({
        url: svcURL,
        type: 'get',
        async: false,//使用同步的方式,true为异步方式
        data: {},//这里使用json对象
        dataType: "json",
        success: function (data) {

            var jsconfig_data = JSON.stringify(data);
            var root = webcfg.getBasePath();

            localStorage.setItem("jsconfig_data_" + root, jsconfig_data);
        },
        fail: function () {
            //code here...
            console.log("cfg加载远程配置失败");
            
        }
    });

}

webcfg.config = function (key) {

    var root = webcfg.getBasePath();
    var jsconfig_data = localStorage.getItem("jsconfig_data_" + root);

    if (!jsconfig_data)
        webcfg.init();

    var config = JSON.parse(jsconfig_data);

    var keys = key.split(".");

    var obj = config;
    var result = "";
    keys.forEach(function (ele, index) {
        result = obj[ele];
        obj = result;
    });

    return result;
}

webcfg.getBasePath = function () {

    var obj = window.location;
    var contextPath = obj.pathname.split("/")[1];
    var basePath = obj.protocol + "//" + obj.host + "/" + contextPath;
    if (basePath.substr(basePath.length - 1, 1) != "/")
        basePath += "/";

    return basePath;
}

webcfg.init();

